/*
 *  Copyright 2011 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.template.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.simpleframework.xml.core.Persister;
import org.simpleframework.xml.stream.Format;

/**
 *
 * @author yura
 */
public class SimpleUtil {

    public static <T> T read(InputStream in, Class<? extends T> type) throws IOException {
        try {
            Persister serializer = new Persister(new Format(Loadable.FORMAT_STR));
            return serializer.read(type, in);
        } catch (Exception ex) {
            throw new IOException(ex);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    //logger.error("Exception throwed during closing of input stream ... ignoring ");
                }
            }
        }
    }

    public static void write(OutputStream out, Object template)
            throws IOException {
        try {
            Persister serializer = new Persister(new Format(Loadable.FORMAT_STR));
            serializer.write(template, out, Loadable.CHARSET);
        } catch (Exception ex) {
            throw new IOException(ex);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    //logger.error("Exception throwed during closing of output stream ... ignoring ");
                }
            }
        }
    }
}
